home *** CD-ROM | disk | FTP | other *** search
- Path: isonews.bbn.hp.com!hpbblb!news
- From: Matthias Dittrich <matti>
- Newsgroups: comp.lang.c
- Subject: Re: Permutations
- Date: 26 Feb 1996 09:51:07 GMT
- Organization: Hewlett-Packard Co.
- Message-ID: <4grvqb$8n9@hpbblb.bbn.hp.com>
- References: <Dn8yz9.GGy@spuddy.mew.co.uk>
- NNTP-Posting-Host: trabant.bbn.hp.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.1N (X11; I; HP-UX A.09.07 9000/712)
- X-URL: news:Dn8yz9.GGy@spuddy.mew.co.uk
-
- david@spuddy.mew.co.uk (David Turner) wrote:
- >Does anyone know of an algorithm that works out the different purmutations
- >of ordering a number of objects? Not calculating how many there are, but
- >actaully working out (quickly?) what they permutations are!
- >
- > eg. permutations of objects A, B and C:
- >
- > A B C B A C C A B
- > A C B B C A C B A
- >
- >Any help would be greatly appreciated.
- >
- >David
- >
- Here is one I've just written:
-
- #include <stdio.h>
- #include <string.h>
-
- #define MAX_PERM 8
-
- void permfunc(unsigned long i, char* str);
- void do_perm(char* str);
-
- int main(int argc, char** argv)
- {
- unsigned long n = 2, i;
- char str[MAX_PERM];
-
- /* do some essential checks */
- if(argc < 2) return 1;
-
- sscanf(argv[1], "%lu", &n);
-
- if(n >= MAX_PERM)
- {
- n = MAX_PERM - 1;
- fprintf(stderr, "number too big, set to %d\n", n);
- }
-
- /* initialize the string to show permutations */
- for(i=0; i<n; i++)
- {
- str[i] = 'A' + i;
- }
- str[n] = '\0';
-
- /* call permfunc with starting level 0 */
- permfunc(0, str);
-
- return 0;
- }
-
- void permfunc(unsigned long i, char* str)
- {
- char s[MAX_PERM];
- char *t = s + i;
- char *u = str + i;
-
- /* check if at least two characters are in the string */
- if(*u && *(u + 1))
- {
- strcpy(s, str);
-
- permfunc(i + 1, s);
- u = t + 1;
-
- /* the number of characters in the string is the number of
- permutations to do */
- while(*u)
- {
- /* after the permutation has been done
- call this function recursively, increasing the starting level */
- do_perm(t);
- permfunc(i + 1, s);
- u++;
- }
- }
- else
- {
- printf("%s\n", str);
- }
- }
-
- /* do the permutation on a string */
- void do_perm(char* str)
- {
- char *s, *t, c;
-
- s = t = str;
- t++;
-
- /* save first char */
- c = *s;
- /* move all chars one position to the left */
- while(*t) *s++ = *t++;
- /* set the last char */
- *s = c;
- }
-
- I think there may be faster ways to do it, but it works.
-
- Good luck,
- Matthias
-
-